package com.zodiac.alioth.service.biz.media;

import com.zodiac.alioth.common.util.FFmpegUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;

@Slf4j
@Service
public class VideoService {

    /**
     * Video Format Conversion
     */
    public String formatConversion(String sourcePath, long fileTime, String filename) {
//        String userId = LoginContextHelper.getLoginUserId() == null ? "sys" : LoginContextHelper.getLoginUserId();
        String userId = "sys";
        String outPath = FFmpegUtil.getExtraPath() + "/out/mao/" + userId + "/" + fileTime;
        File f = new File(outPath);
        String outFileName = outPath + "/" + filename;
        if (!f.exists()) {
            boolean mkdirs = f.mkdirs();
        }
        String fFmpeg = FFmpegUtil.getExtraPath() + "/ffmpeg";
        String ffmpeg = "ffmpeg";
        // ffmpeg -i areyoureal.mp4 -map 0 -map 0 -b:v:0 800k -b:v:1 300k -s:v:1 320*170 -f dash output/manifest.mpd
//        String cmd = fFmpeg + " -i " + sourcePath + " -f dash " + outFileName;
        String cmd = fFmpeg + " -y -i " + sourcePath + " -map 0 -s:v:0 1920*1080 " +
                "-map 0 -s:v:1 1280*720 " +
                "-map 0 -s:v:2 854*480 " +
                "-map 0 -s:v:3 640*360 " +
                "-c:v libx264 " + " -f dash " + outFileName;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);

            InputStream errorStream = process.getErrorStream();
            if (errorStream != null) {
                byte[] bytes = new byte[errorStream.available()];
                errorStream.read(bytes);
                String errResult = new String(bytes);
                log.error("ffmpeg error, result={}", errResult);
            }

            OutputStream outputStream = process.getOutputStream();
            if (outputStream != null) {
//                OutputStreamWriter outw = null;
//                outw = new OutputStreamWriter(outputStream);
//                String str = null;
//                outw.write(str);
//                outw.close();
//                outputStream.flush();
//                outputStream.close();

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                outputStream.write(baos.toByteArray());
                String str = baos.toString();

                outputStream.flush();
                outputStream.close();

                log.info("ffmpeg error, result={}", str);
            }
            process.waitFor();
            int i = process.exitValue();
            log.info("exit ffmpeg, exitValue={}", i);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            log.error("ffmpeg process error, e={}", e.getMessage(), e);
        }
        log.info("outFileName={}", outFileName);
        return outFileName;
    }

}
